package com.chat.client.control;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.StringTokenizer;

import android.os.Handler;

// 채팅서버와 연결하고, 데이터를 송신
public class ChatSender implements IChatProtocal {
	
	public static final String TAG = ChatSender.class.getSimpleName();
	
	private Socket socket ;
	private PrintWriter out;
	private ChatListener listener;
	
	public ChatSender(String serverIP, int serverPort, Handler handler) throws UnknownHostException, IOException{
		socket = new Socket(serverIP, serverPort);
		out = new PrintWriter(socket.getOutputStream(), true);
		// 채팅 리스너 생성
		listener = new ChatListener(socket, handler);
		listener.start();
	}
	
	// 대기실 입장 메시지(1000||대화명) 서버에 전송
	public void chatEntry(String nickName) {
		sendMessage(CHAT_TYPE_ENTER+"||"+nickName);		
	}
	
	// 대기실 나가기
	public void chatOut(String nickName){
		sendMessage(CHAT_TYPE_OUT+"||"+nickName);		
		disConnect();
	}
	
	public void sendMessage(String nickName, String message){
		// 쪽지 메시지인 경우
		if(message.startsWith("/")){
			// /send 받는사람 메시지
			StringTokenizer st = new StringTokenizer(message);
			String comand = st.nextToken();
			String receiveNickName = st.nextToken();
			String sendMessage = st.nextToken();
			sendMessage(CHAT_TYPE_GWIT+"||" + nickName + "||" + 
					           receiveNickName+"||" + sendMessage);
		}else{			
			sendMessage(CHAT_TYPE_CHAT+"||"+ nickName + "||"+message);
		}
	}
	
	// 채팅서버에 클라이언트 메시지 전송
	private void sendMessage(String message){
		// 서버로 전송
		out.println(message);
	}
	
	// 연결 끊기
	private void disConnect(){
		try {
			socket.close();
		} catch (IOException e) {}
	}

}
